// 录制服务
// 调用后端Playwright命令进行录制

import { recordingManager } from './recordingManager.js'

/**
 * 录制服务类
 * 作为recordingManager的封装层，提供录制功能
 */
export class RecordingService {
  constructor() {
    // 使用recordingManager作为底层实现
    this.manager = recordingManager
    
    // 保持兼容性的属性代理
    this.API_BASE_URL = 'http://localhost:8080/api/commands/recording'
    this.BACKEND_API_URL = 'http://localhost:8080/api/commands'
  }
  
  // 代理属性到manager
  get isRecording() {
    return this.manager.isRecording
  }
  
  get recordingSteps() {
    return this.manager.recordedSteps
  }
  
  get currentSessionId() {
    return this.manager.sessionId
  }
  
  get recordingSession() {
    return this.manager.recordingSession
  }
  

  /**
   * 初始化录制功能
   */
  async init() {
    try {
      await this.manager.init()
      console.log('录制功能初始化完成')
    } catch (error) {
      console.error('录制功能初始化失败:', error)
    }
  }

  /**
   * 开始录制
   */
  async startRecording(url = 'https://www.baidu.com') {
    try {
      console.log('准备开始录制:', url)
      
      // 调用manager的startRecording方法
      const result = await this.manager.startRecording(url)
      
      return result
      
    } catch (error) {
      console.error('启动录制失败:', error)
      return {
        success: false,
        error: '启动录制失败: ' + error.message
      }
    }
  }

  /**
   * 停止录制并自动导入脚本
   */
  async stopRecording() {
    try {
      console.log('停止录制...')
      
      // 调用manager的stopRecording方法
      const result = await this.manager.stopRecording()
      
      if (!result.success) {
        return result
      }
      
      // 生成脚本
      let script = null
      const steps = result.steps || []
      
      if (steps.length > 0) {
        script = this.generateScriptFromSteps(steps)
      }
      
      // 清除sessionStorage中的录制状态
      if (typeof window !== 'undefined') {
        sessionStorage.removeItem('isRecording')
        sessionStorage.removeItem('currentSessionId')
        sessionStorage.removeItem('recordingUrl')
        sessionStorage.removeItem('recordingStartTime')
      }
      
      console.log('录制停止完成，模式:', result.mode)
      
      return {
        success: true,
        steps: steps,
        script: script,
        sessionId: result.sessionId,
        mode: result.mode || 'codegen',
        message: '录制完成！已获取Playwright录制结果。'
      }
      
    } catch (error) {
      console.error('停止录制失败:', error)
      return {
        success: false,
        error: '停止录制失败: ' + error.message
      }
    }
  }

  /**
   * 强制清理录制状态
   */
  forceCleanupRecording() {
    this.manager.forceCleanup()
    
    // 清理sessionStorage
    if (typeof window !== 'undefined') {
      sessionStorage.removeItem('isRecording')
      sessionStorage.removeItem('currentSessionId')
      sessionStorage.removeItem('recordingUrl')
    }
    
    console.log('录制状态清理完成')
  }

  /**
   * 重新初始化录制功能
   */
  reinitializeRecorder() {
    console.log('重新初始化录制功能...')
    
    this.forceCleanupRecording()
    
    setTimeout(() => {
      this.init()
      console.log('录制功能重新初始化完成')
    }, 100)
  }

  /**
   * 获取录制状态
   */
  getRecordingStatus() {
    return this.manager.getRecordingStatus()
  }

  /**
   * 暂停录制
   */
  pauseRecording() {
    return this.manager.pauseRecording()
  }

  /**
   * 恢复录制
   */
  resumeRecording() {
    return this.manager.resumeRecording()
  }

  /**
   * 更新录制状态
   */
  updateRecordingStatus() {
    // 触发状态更新事件
    if (typeof window !== 'undefined') {
      const event = new CustomEvent('recordingStatusUpdated', {
        detail: {
          isRecording: this.isRecording,
          stepCount: this.recordingSteps.length,
          sessionId: this.currentSessionId,
          steps: this.recordingSteps
        }
      })
      window.dispatchEvent(event)
    }
  }

  /**
   * 从录制步骤生成Playwright脚本
   */
  generateScriptFromSteps(steps) {
    const url = (typeof window !== 'undefined' && sessionStorage.getItem('recordingUrl')) || 'https://www.baidu.com'
    
    let scriptContent = `import { test, expect } from '@playwright/test';

test('录制脚本_${new Date().toLocaleString()}', async ({ page }) => {
  // 导航到页面
  await page.goto('${url}');
`
    
    // 处理录制的步骤
    steps.forEach((step, index) => {
      switch (step.type) {
        case 'navigation':
          if (step.url && step.url !== url) {
            scriptContent += `  
  // ${step.description || step.name || '导航'}
  await page.goto('${step.url}');`
          }
          break
          
        case 'click':
          scriptContent += `  
  // ${step.description || step.name || '点击元素'}
  await page.click('${step.selector || step.locator}');`
          break
          
        case 'input':
        case 'fill':
          scriptContent += `  
  // ${step.description || step.name || '输入文本'}
  await page.fill('${step.selector || step.locator}', '${step.value || step.text || ''}');`
          break
          
        case 'type':
          scriptContent += `  
  // ${step.description || step.name || '输入文本'}
  await page.type('${step.selector || step.locator}', '${step.value || step.text || ''}');`
          break
          
        case 'select':
          scriptContent += `  
  // ${step.description || step.name || '选择选项'}
  await page.selectOption('${step.selector || step.locator}', '${step.value || ''}');`
          break
          
        case 'wait':
          if (step.selector || step.locator) {
            scriptContent += `  
  // ${step.description || step.name || '等待元素'}
  await page.waitForSelector('${step.selector || step.locator}');`
          } else {
            scriptContent += `  
  // ${step.description || step.name || '等待'}
  await page.waitForTimeout(${step.value || step.timeout || 1000});`
          }
          break
          
        case 'assertion':
        case 'expect':
          if (step.assertion === 'toBeVisible' || step.type === 'visible') {
            scriptContent += `  
  // ${step.description || step.name || '验证元素可见'}
  await expect(page.locator('${step.selector || step.locator}')).toBeVisible();`
          } else if (step.assertion === 'toHaveText' || step.type === 'text') {
            scriptContent += `  
  // ${step.description || step.name || '验证文本内容'}
  await expect(page.locator('${step.selector || step.locator}')).toHaveText('${step.value || step.text || ''}');`
          } else {
            scriptContent += `  
  // ${step.description || step.name || '验证元素'}
  await expect(page.locator('${step.selector || step.locator}')).${step.assertion || 'toBeVisible'}();`
          }
          break
          
        default:
          if (step.code) {
            scriptContent += `  
  // ${step.description || step.name || '自定义操作'}
  ${step.code}`
          }
      }
    })
    
    scriptContent += `
});`
    
    return scriptContent
  }
  

  /**
   * 自动导入生成的脚本
   */
  autoImportGeneratedScript(scriptContent) {
    // 解析脚本并返回步骤
    const steps = this.manager.parseScriptToSteps(scriptContent)
    
    return {
      success: true,
      steps: steps,
      message: `成功解析 ${steps.length} 个步骤`
    }
  }

}

// 创建单例实例
export const recordingService = new RecordingService()

// 导出便捷方法
export const startRecording = (url) => recordingService.startRecording(url)
export const stopRecording = () => recordingService.stopRecording()
export const forceCleanupRecording = () => recordingService.forceCleanupRecording()
export const reinitializeRecorder = () => recordingService.reinitializeRecorder()
export const getRecordingStatus = () => recordingService.getRecordingStatus()
export const autoImportGeneratedScript = (scriptContent) => recordingService.autoImportGeneratedScript(scriptContent)